<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>管理员端口列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索 -->
    <el-form :inline="true" style="margin-top: 20px;">
      <el-form-item>
        <el-button size="small" @click="exportExcel">导出Excel</el-button>
      </el-form-item>
      <el-form-item>
        <el-input
          size="small"
          v-model="portName"
          placeholder="请输入端口名称"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select
          size="small"
          v-model="portStatus"
          placeholder="请选择端口状态"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select size="small" v-model="electricX" placeholder="请选择充电桩">
          <el-option
            v-for="item in options4"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          size="small"
          v-model="stationStatus"
          placeholder="请选择充电桩状态"
        >
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          size="small"
          v-model="siteStatus"
          placeholder="请选择站点状态"
        >
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item>
                <el-input size="small" v-model="userName" placeholder="请输入桩主用户名"></el-input>
            </el-form-item> -->
      <el-form-item>
        <el-input
          size="small"
          v-model="userPhone"
          placeholder="请输入桩主手机号"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item>
                <el-select size="small" v-model="userType" placeholder="请选择是否平台合伙人">
                    <el-option v-for="item in options3" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item> -->
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="chongzhi"
          >重置</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="upPort()"
          >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table
      size="small"
      ref="multipleTable"
      :data="portData"
      element-loading-text="拼命加载中"
      style="width: 100%;"
      v-horizontal-scroll
    >
      <el-table-column
        align="center"
        sortable
        type="index"
        label="序号"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="portName"
        label="端口名称"
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="portStatus"
        :formatter="PortStatus"
        label="端口状态"
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="terminalNum"
        label="设备号"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="num"
        label="枪号"
      ></el-table-column>
      <!-- <el-table-column align="center" sortable prop="price" label="价格(元/度)" width="120">
                <template slot-scope="scope">
                    <div>{{ scope.row.price / 100 }}</div>
                </template>
</el-table-column> -->
      <el-table-column align="center" sortable prop="voltage" label="电压">
        <template slot-scope="scope">
          <div>{{ scope.row.voltage / 100 }}</div>
        </template>
      </el-table-column>

      <el-table-column align="center" sortable prop="current" label="电流">
        <template slot-scope="scope">
          <div>{{ scope.row.current / 100 }}</div>
        </template>
      </el-table-column>

      <el-table-column align="center" sortable prop="power" label="功率">
        <template slot-scope="scope">
          <div>{{ scope.row.power / 100 }}</div>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="type"
        label="类型"
        width="120"
      ></el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="siteName"
        label="站点名称"
        width="120"
      ></el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="siteStatus"
        label="站点状态"
        :formatter="siteStatusS"
        width="120"
      ></el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="stationName"
        label="充电桩名称"
        width="120"
      ></el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="factoryType"
        label="厂家类型"
        width="150"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.factoryType == 0">科土达</div>
          <div v-if="scope.row.factoryType == 1">星星充电</div>
          <div v-if="scope.row.factoryType == 2">公牛</div>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="stationStatus"
        label="充电桩状态"
        :formatter="StationStatus"
        width="120"
      ></el-table-column>
      <!-- <el-table-column align="center" sortable prop="userName" label="桩主用户名" width="120"></el-table-column> -->
      <el-table-column
        align="center"
        sortable
        prop="phone"
        label="桩主手机号"
        width="120"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="createTime"
        label="创建时间"
        width="150"
      >
        <template slot-scope="scope">
          <div>{{ transformDate(scope.row.createTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="500">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="openPrice(scope.row)"
            >设置预约充电押金</el-button
          >
          <el-button size="mini" type="primary" @click="openPort(scope.row)"
            >查看详情</el-button
          >
          <el-button size="mini" type="success" @click="openQrCode(scope.row)"
            >查看二维码</el-button
          >

          <el-button size="mini" type="primary" @click="upPort(scope.row)"
            >修改</el-button
          >
          <el-button size="mini" type="danger" @click="delePort(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看详情 -->
    <el-dialog title="端口详情页：" :visible.sync="editFormDetails">
      <el-form label-width="150px">
        <el-form-item label="端口名称：">
          <span v-html="this.Details.portName"></span>
        </el-form-item>

        <el-form-item label="端口状态：">
          <span v-if="this.Details.portStatus == 0">空闲</span>
          <span v-if="this.Details.portStatus == 1">使用中</span>
          <span v-if="this.Details.portStatus == 2">故障</span>
          <span v-if="this.Details.portStatus == 3">离线</span>
        </el-form-item>

        <el-form-item label="设备号：">
          <span v-html="this.Details.terminalNum"></span>
        </el-form-item>
        <el-form-item label="枪号：">
          <span v-html="this.Details.num"></span>
        </el-form-item>
        <!-- <el-form-item label="价格（元/度）：">
                    <span v-html="this.Details.price / 100"></span>
                </el-form-item> -->
        <el-form-item label="电压：">
          <span v-html="this.Details.voltage / 100"></span>
        </el-form-item>
        <el-form-item label="电流：">
          <span v-html="this.Details.current / 100"></span>
        </el-form-item>
        <el-form-item label="功率：">
          <span v-html="this.Details.power / 100"></span>
        </el-form-item>
        <el-form-item label="类型：">
          <span v-html="this.Details.type"></span>
        </el-form-item>
        <el-form-item label="站点名称：">
          <span v-html="this.Details.siteName"></span>
        </el-form-item>
        <el-form-item label="站点状态：">
          <span v-if="this.Details.siteStatus == 0">开放</span>
          <span v-if="this.Details.siteStatus == 1">休息</span>
          <span v-if="this.Details.siteStatus == 2">故障</span>
          <span v-if="this.Details.siteStatus == 3">认领</span>
        </el-form-item>
        <el-form-item label="充电桩名称：">
          <span v-html="this.Details.stationName"></span>
        </el-form-item>
        <el-form-item label="充电桩状态：">
          <span v-if="this.Details.stationStatus == 0">开放</span>
          <span v-if="this.Details.stationStatus == 1">休息</span>
          <span v-if="this.Details.stationStatus == 2">故障</span>
        </el-form-item>
        <!-- <el-form-item label="桩主用户名：">
                    <span v-html="this.Details.userName"></span>
                </el-form-item> -->
        <el-form-item label="桩主手机号：">
          <span v-html="this.Details.phone"></span>
        </el-form-item>
        <el-form-item label="创建时间：" prop="createTime">
          {{ transformDate(this.Details.createTime) }}
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑界面 -->
    <el-dialog :title="tit" :visible.sync="editFormVisiible" width="30%">
      <el-form label-width="100px">
        <el-form-item label="充电桩名称">
          <el-select v-model="xiugai.stationId" placeholder="请选择充电桩名称">
            <el-option
              v-for="item in options4"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="厂家类型">
          <el-select v-model="xiugai.factoryType" placeholder="请选择厂家类型">
            <el-option
              v-for="item in factoryArray"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="端口名">
          <el-input
            size="small"
            v-model="xiugai.portName"
            auto-complete="off"
            placeholder="请输入端口名"
          ></el-input>
        </el-form-item>
        <el-form-item label="设备号">
          <el-input
            size="small"
            v-model="xiugai.terminalNum"
            auto-complete="off"
            placeholder="请输入设备号"
          ></el-input>
        </el-form-item>
        <el-form-item label="枪号">
          <el-input
            size="small"
            v-model="xiugai.num"
            auto-complete="off"
            placeholder="请输入枪号"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="xiugai.portStatus"
            placeholder="请选择充电桩状态"
            size="small"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog()">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="addPorts()"
          v-if="tit == '添加'"
          >添加</el-button
        >
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="upPorts()"
          v-if="tit == '修改'"
          >修改</el-button
        >
      </div>
    </el-dialog>
    <!-- 二维码 -->
    <el-dialog title="二维码" :visible.sync="editFormEqCode" width="30%">
      <div class="er-code-option">
        <el-image :src="qrCodeSrc" fit="fill" class="img"></el-image>
      </div>
    </el-dialog>
    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>
  </div>
</template>

<script>
import Pagination from "../../components/Pagination";
import {
  getAdminStationPortList,
  getAdminStationPortInfo,
  addAdminStationPort,
  deAdminStationPort,
  upAdminStationPort,
  getStationAdminList,
  getAdminStationPortListHttp
} from "../../api/userMG";
import QRCode from "qrcode";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
export default {
  data() {
    return {
      editFormEqCode: false,
      qrCodeSrc: "", //二维码地址
      portData: [],
      loading: false,
      siteId: "",
      siteStatus: "",
      stationId: "",
      stationStatus: "",
      portName: "",
      portStatus: "",
      userId: -1,
      userPhone: "",
      userName: "",
      userType: "",
      options: [
        {
          value: 0,
          label: "空闲"
        },
        {
          value: 1,
          label: "使用中"
        },
        {
          value: 2,
          label: "故障"
        },
        {
          value: 3,
          label: "离线"
        }
      ],
      options1: [
        {
          value: 0,
          label: "开放"
        },
        {
          value: 1,
          label: "休息"
        },
        {
          value: 2,
          label: "故障"
        }
      ],
      options2: [
        {
          value: 0,
          label: "开放"
        },
        {
          value: 1,
          label: "休息"
        },
        {
          value: 2,
          label: "故障"
        },
        {
          value: 3,
          label: "认领"
        }
      ],
      options3: [
        {
          value: 0,
          label: "普通合伙人"
        },
        {
          value: 1,
          label: "平台合伙人"
        }
      ],
      editFormDetails: false,
      Details: [],
      editFormVisiible: false,
      xiugai: {
        id: "",
        stationId: "",
        portName: "",
        terminalNum: "",
        num: "",
        portStatus: "",
        createTime: "",
        factoryType: ""
      },
      factoryType: "", //
      factoryArray: [
        {
          label: "科士达",
          value: 0
        },
        {
          label: "星星充电",
          value: 1
        },
        {
          label: "公牛",
          value: 2
        }
      ],
      tit: "添加",
      options4: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 20,
        total: 10
      },
      electricX: ""
    };
  },
  // 注册组件
  components: {
    Pagination
  },
  created() {
    this.getdata(1);
    this.gteElectricPile();
  },
  methods: {
    // 二维码
    openQrCode(row) {
      this.editFormEqCode = true;
      let url = `${this.$erCodeUrl}${row.stationId}`;

      this.$nextTick(() => {
        this.generateQRCode(url);
      });
    },
    // 跳转页面
    openPrice(row) {
      var userdata = JSON.parse(localStorage.getItem("userdata"));
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: "不可以空数据提交!"
      })
        .then(({ value }) => {
          if (value === userdata.menuTwo) {
            setTimeout(() => {
              this.loading = false;
              // 跳转页面
              this.$router.push({
                path: "/adminCharging/AdminPortReservation",
                query: {
                  id: row.id
                }
              });
            });
          } else {
            this.$message({
              type: "error",
              message: "密码错误"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.page = parm.currentPage;
      this.getdata(parm.currentPage);
    },
    exportExcel() {
      var parameter = {
        page: -2,
        siteId: this.siteId,
        siteStatus: this.siteStatus,
        stationId: this.stationId,
        stationStatus: this.stationStatus,
        portName: this.portName,
        portStatus: this.portStatus,
        userId: this.userId,
        userPhone: this.userPhone,
        userName: this.userName,
        userType: this.userType,
        stationId: this.electricX
      };
      // getAdminStationPortList(parameter).then(res => {
      getAdminStationPortListHttp(parameter).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          this.portData = res.data.list;
          return;
        }
      });
      setTimeout(() => {
        //转换成excel时，使用原始的格式
        var xlsxParam = { raw: true };
        let fix = document.querySelector(".el-table__fixed-right");
        let wb;
        //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
        if (fix) {
          wb = XLSX.utils.table_to_book(
            this.$refs.multipleTable.$el.removeChild(fix),
            xlsxParam
          );
          this.$refs.multipleTable.$el.appendChild(fix);
        } else {
          wb = XLSX.utils.table_to_book(
            this.$refs.multipleTable.$el,
            xlsxParam
          );
        }
        var wbout = XLSX.write(wb, {
          bookType: "xls",
          bookSST: true,
          type: "array"
        });
        try {
          // 如果是IE浏览器，使用Blob通过navigator.msSaveBlob保存
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(
              new Blob([wbout], { type: "application/octet-stream" }),
              "管理员端口列表.xlsx"
            );
          } else {
            // 在其他浏览器中使用file-saver保存文件
            saveAs(
              new Blob([wbout], { type: "application/octet-stream" }),
              "管理员端口列表.xlsx"
            );
          }
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, wbout);
        }
        return wbout;
      }, 1000);
      setTimeout(() => {
        this.getdata(1);
      }, 2000);
    },
    generateQRCode(data) {
      QRCode.toDataURL(data)
        .then(url => {
          this.qrCodeSrc = url;
        })
        .catch(err => {
          console.error(err);
        });
    },
    // 获取充电桩列表
    gteElectricPile() {
      getStationAdminList({
        userId: -1
      }).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          res.data.list.forEach(item => {
            this.options4.push({ label: item.stationName, value: item.id });
          });
          return;
        }
      });
    },
    // 修改
    upPorts() {
      this.loading = true;
      upAdminStationPort(this.xiugai).then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.editFormVisiible = false;
          this.$message.success(res.msg);
          this.getdata(this.pageparm.currentPage);
        } else {
          this.editFormVisiible = false;
          this.$message.error(res.msg);
        }
      });
    },
    // 添加
    addPorts() {
      this.loading = true;
      addAdminStationPort(this.xiugai).then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.editFormVisiible = false;
          this.$message.success(res.msg);
          this.getdata(1);
        } else {
          this.editFormVisiible = false;
          this.$message.error(res.msg);
        }
      });
    },
    // 打开编辑器
    upPort(row) {
      var userdata = JSON.parse(localStorage.getItem("userdata"));
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: "不可以空数据提交!"
      })
        .then(({ value }) => {
          if (value === userdata.menuTwo) {
            this.editFormVisiible = true;
            if (row != undefined && row != "undefined") {
              this.tit = "修改";
              this.xiugai.id = row.id;
              this.xiugai.stationId = row.stationId;
              this.xiugai.portName = row.portName;
              this.xiugai.terminalNum = row.terminalNum;
              this.xiugai.num = row.num;
              this.xiugai.portStatus = row.portStatus;
              this.xiugai.createTime = row.createTime;
              this.xiugai.factoryType = row.factoryType;
            } else {
              this.tit = "添加";
              this.xiugai.id = "";
              this.xiugai.stationId = "";
              this.xiugai.portName = "";
              this.xiugai.terminalNum = "";
              this.xiugai.num = "";
              this.xiugai.portStatus = "";
              this.xiugai.createTime = "";
              this.xiugai.factoryType = "";
            }
          } else {
            this.$message({
              type: "error",
              message: "密码错误"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    // 关闭编辑对话框
    closeDialog() {
      this.editFormVisiible = false;
      this.$message({
        type: "info",
        message: "已取消编辑"
      });
    },
    // 删除
    delePort(row) {
      var userdata = JSON.parse(localStorage.getItem("userdata"));
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^(?!(\s+$))/,
        inputErrorMessage: "不可以空数据提交!"
      })
        .then(({ value }) => {
          if (value === userdata.menuTwo) {
            this.$confirm("确定删除吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "error"
            })
              .then(() => {
                let data = {
                  id: row.id
                };
                deAdminStationPort(data).then(res => {
                  if (res.code == 200) {
                    this.$message.success(res.msg);
                    this.getdata(this.pageparm.currentPage);
                  } else {
                    this.$message.error(res.msg);
                  }
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消删除"
                });
              });
          } else {
            this.$message({
              type: "error",
              message: "密码错误"
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    // 充电桩状态
    StationStatus: function(row) {
      if (row.stationStatus == 0) {
        return "开放";
      } else if (row.stationStatus == 1) {
        return "休息";
      } else if (row.stationStatus == 2) {
        return "故障";
      }
    },
    // 站点状态
    siteStatusS: function(row) {
      if (row.siteStatus == 0) {
        return "开放";
      } else if (row.siteStatus == 1) {
        return "休息";
      } else if (row.siteStatus == 2) {
        return "故障";
      } else if (row.siteStatus == 3) {
        return "认领";
      }
    },
    // 是否为平台合伙人
    userTypeS: function(row) {
      if (row.userType == 0) {
        return "普通合伙人";
      } else if (row.userType == 1) {
        return "平台合伙人";
      }
    },
    // 端口状态
    PortStatus: function(row) {
      if (row.portStatus == 0) {
        return "空闲";
      } else if (row.portStatus == 1) {
        return "使用中";
      } else if (row.portStatus == 2) {
        return "故障";
      } else if (row.portStatus == 3) {
        return "离线";
      }
    },
    // 打开详情页面
    openPort(row) {
      this.loading = true;
      this.editFormDetails = true;
      let data = {
        id: row.id
      };
      getAdminStationPortInfo(data).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          this.Details = res.data.data;
          return;
        }
      });
    },
    // 搜索数据
    search() {
      this.getdata(1);
    },
    // 重置数据
    chongzhi() {
      this.siteId = "";
      this.siteStatus = "";
      this.stationId = "";
      this.stationStatus = "";
      this.portName = "";
      this.portStatus = "";
      this.userId = -1;
      this.userPhone = "";
      this.userName = "";
      this.userType = "";
      this.electricX = "";
      this.getdata(1);
    },
    // 获取数据
    getdata(page) {
      this.loading = true;
      var parameter = {
        page: (page - 1) * 20,
        siteId: this.siteId,
        siteStatus: this.siteStatus,
        stationId: this.stationId,
        stationStatus: this.stationStatus,
        portName: this.portName,
        portStatus: this.portStatus,
        userId: this.userId,
        userPhone: this.userPhone,
        userName: this.userName,
        userType: this.userType,
        stationId: this.electricX
      };
      // getAdminStationPortList(parameter).then(res => {
        getAdminStationPortListHttp(parameter).then(res => {
        this.loading = false;
        if (res.code != 200) {
          this.$Message({
            type: "info",
            message: res.msg
          });
        } else {
          this.portData = res.data.list;
          this.pageparm.currentPage = page;
          this.pageparm.total = res.data.count;
          return;
        }
      });
    }
  }
};
</script>

<style>
.er-code-option {
  display: flex;
  align-items: center;
  justify-content: center;
}

.img {
  width: 200px;
  height: 200px;
}
</style>
